package com.kawins.spring;

import com.kawins.util.encrypt.DES;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 获取配置文件properties文件数据
 *
 * @author rankai
 *         createTime 2017-09-2017/9/6 9:56
 */
public class ContextProperty extends PropertyPlaceholderConfigurer {

    private static final Map<String, Object> ctxPropertiesMap = new HashMap<>();

    private static boolean encrypt = false;

    private static String desKey;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        super.processProperties(beanFactory, props);
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String property = props.getProperty(keyStr);
            if (StringUtils.isNotBlank(desKey)) {
                ctxPropertiesMap.put(keyStr, encrypt ? DES.decryptDES(property, desKey) : property);
            } else {
                ctxPropertiesMap.put(keyStr, encrypt ? DES.decryptDES(property) : property);
            }
        }
    }

    /**
     * 通配符加载Properties文件
     *
     * @param locations
     * @throws IOException
     */
    public void setStrLocations(String... locations) throws IOException {
        Resource[] resourcesAll = new Resource[0];
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        for (int i = 0; i < locations.length; i++) {
            Resource[] resources = resolver.getResources(locations[i]);
            resourcesAll = ArrayUtils.addAll(resourcesAll, resources);
        }
        super.setLocations(resourcesAll);
    }


    /**
     * properties文件读取
     *
     * @param name 名称
     * @return 名称对应值
     */
    public static Object getContextProperty(String name) {
        return ctxPropertiesMap.get(name);
    }

    public static void setEncrypt(boolean encrypt) {
        ContextProperty.encrypt = encrypt;
    }

    public static void setDesKey(String desKey) {
        ContextProperty.desKey = desKey;
    }
}
